package com.gitee.openviducn.inspector.rest;

import com.gitee.openviducn.inspector.auth.AuthService;
import com.gitee.openviducn.inspector.auth.JwtUtil;
import com.gitee.openviducn.inspector.auth.SimpleWebAuthServiceImpl;
import com.gitee.openviducn.inspector.common.BizException;
import com.gitee.openviducn.inspector.common.ResponseError;
import com.gitee.openviducn.inspector.constant.AppConstant;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: https://gitee.com/wesleyOne
 * @Date: 02.26 2020
 */
public class BaseController {

    private AuthService.AuthUser getAuthUser(HttpServletRequest request) {
        String token = request.getHeader(AppConstant.HEADER_TOKEN);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        Map<String, String> claims = JwtUtil.getClaims(token);
        if (Objects.isNull(claims) || claims.isEmpty()) {
            return null;
        }
        String userId = claims.get(AuthService.USER_ID);
        String username = claims.get(AuthService.USERNAME);
        String role = claims.get(AuthService.ROLE);
        AuthService.SystemRole systemRole = AuthService.SystemRole.valueOf(role);
        return new SimpleWebAuthServiceImpl.SimpleWebAuthUserImpl(Long.parseLong(userId), username, systemRole);
    }

    /**
     * 获取用户帐号
     */
    String getUsername(HttpServletRequest request) throws BizException {
        try {
            return getAuthUser(request).getUsername();
        } catch (Exception e) {
            throw new BizException(ResponseError.AUTH_CA_ERROR);
        }
    }

    /**
     * 获取用户帐号
     */
    Long getUserId(HttpServletRequest request) throws BizException {
        try {
            return getAuthUser(request).getId();
        } catch (Exception e) {
            throw new BizException(ResponseError.AUTH_CA_ERROR);
        }
    }

}
